package com.zhxin.nettylab.nio.chapter1;

import java.nio.CharBuffer;

/**
 * @ClassName BufferTest
 * @Description //BufferTest
 * @Author singleZhang
 * @Email 405780096@qq.com
 * @Date 2020/12/3 0003 下午 4:03
 **/
public class BufferTest {

    public static void main(String[] args){

        //创建Buffer,capacity为10
        CharBuffer cbf = CharBuffer.allocate(10);

        System.out.println(cbf.capacity()); //容量：10
        System.out.println(cbf.limit());    //读写限制:10
        System.out.println(cbf.position()); //读写位置:0 起始值

        cbf.put("a");
        cbf.put("b");
        cbf.put("c");
        System.out.println(cbf.position()); //输出3

        cbf.flip(); //buffer从写入转换成读取,把limit设置为position,把position还原成0

        System.out.println(cbf.position());
        System.out.println(cbf.limit());

        //取值
        System.out.println(cbf.get()); //取第一个元素 a
        System.out.println(cbf.position()); //读写位置变为1

        cbf.clear(); //clear方法将limit设置成capacity,position设置成0
        System.out.println(cbf.limit());
        System.out.println(cbf.position());
        System.out.println(cbf.get(2)); //读取第三个元素c

        System.out.println(cbf.position());//读写位置不变，get方法加了索引值,根据索引来取值不影响position

        System.out.println(cbf.get());
        System.out.println(cbf.get());
        cbf.mark(); //标记
        System.out.println(cbf.position());  //标记后的位置为2
        System.out.println(cbf.get());
        System.out.println(cbf.position());
        cbf.reset();//返回标记
        System.out.println(cbf.position()); //返回标记的位置2

        cbf.clear();//读取完成后，调用Buffer.clear() 或Buffer.compact()方法，将缓冲区转换为写入模式
        System.out.println(cbf.limit());
        System.out.println(cbf.position());
        System.out.println(cbf.capacity());
    }

}
